package com.qiji.video.web.controller;

import com.qiji.video.bean.Admins;
import com.qiji.video.bean.Users;
import com.qiji.video.bean.dto.LoginDto;
import com.qiji.video.config.MyRealm;
import com.qiji.video.exception.ServiceException;
import com.qiji.video.service.IAdminService;
import com.qiji.video.service.IUserService;
import com.qiji.video.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.mail.MessagingException;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录模块
 */
@RestController
@RequestMapping("/login")
@Api(tags = "登录模块")
public class  LoginController {

    @Autowired
    private IUserService userService;
    @Autowired
    private IAdminService adminService;
    @Autowired
    private MyRealm myRealm;

    @PostMapping("/userLogin")
    @ApiOperation("用户登录(手机号或邮箱)")
    public Result userLogin(LoginDto loginDto) throws ServiceException {
        // 获取当前操作对象
        Subject subject = SecurityUtils.getSubject();
        String username = loginDto.getUsername();
        String md5Pwd = Md5Util.getMd5Key(loginDto.getPassword());
        UsernamePasswordToken token = new UsernamePasswordToken(username, md5Pwd);

        subject.login(token);
        // 返回jwt
        return ResultUtil.success(myRealm.getJwt(username));
//        // 获取当前操作对象
//        Users user = userService.userLogin(loginDto.getUsername(),loginDto.getPassword());
//        HashMap map=new HashMap();
//        map.put("role",user.getRole());
//        return ResultUtil.success(JwtUtil.sign(user.getId().toString(),map));
    }

    /**
     * 登录错误写法，token的存储应该交给前端，token不能存储在服务端
     * @param
     * @return
     * @throws ServiceException
     */
    @PostMapping("/adminLogin")
    @ApiOperation("管理员登录(邮箱或手机号)")
    public Result adminLogin(LoginDto loginDto) throws ServiceException {
        Admins admins = adminService.adminLogin(loginDto.getUsername(),loginDto.getPassword());
        Map map = new HashMap();
        map.put("role",admins.getRole());
        String token = JwtUtil.sign(admins.getId().toString(),map);

        return ResultUtil.success(token);

//        return null;

    }
    // 发送邮箱
    @PostMapping("/email")
    public Result getEmail(String email) throws MessagingException {
        userService.sendEmail(email);
        return new Result(ResultCode.SUCCESS);
    }
}